package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.admin.feign.ArticleFeign;
import com.heima.admin.feign.WemediaFeign;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.aliyun.GreenUrlImageScan;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.admin.pojos.AdSensitive;
import com.heima.model.article.datos.ArticelDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author feng js
 */
@Service
@Transactional
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    WemediaFeign wemediaFeign;

    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        if (id == null) {
            throw new RuntimeException("id为空");
        }
        WmNews wmNews = wemediaFeign.findByIdWmNews(id);
        if (wmNews == null) {
            throw new RuntimeException("当前文章不存在");
        }
        //自媒体文章状态为4（人工审核通过）直接保存
        if (wmNews.getStatus() == 4 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            saveAppArticel(wmNews);
            return;
        }
        //自媒体文章状态为8（审核通过未发布）直接保存
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            saveAppArticel(wmNews);
            return;
        }
        //未审核
        if (wmNews.getStatus() == 1) {
            //获取图片和文章内容
          Map<String,Object> resultMap = handleTextAndImages(wmNews);
          //阿里云内容审核
            String content = (String) resultMap.get("content");
           boolean textScan = handleTextScan(content,wmNews);
            if (!textScan) {
                return;
            }
            //阿里云图片审核
            List<String> images = (List<String>) resultMap.get("image");
           boolean imageScan = handleimageScan(images,wmNews);
            if (!imageScan) {
                return;
            }
            //自定义敏感词审核
            boolean sensitive =  handleSensitive(content,wmNews);
            if (!sensitive) {
                return;
            }

            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()) {
                updateWmNews(wmNews,(short)8,"审核通过");
                return;
            }
            saveAppArticel(wmNews);

        }
    }
    @Autowired
    AdSensitiveMapper adSensitiveMapper;

    /**
     * 自定义敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        List<AdSensitive> dbsensitives = adSensitiveMapper.selectList(Wrappers.<AdSensitive>lambdaQuery().select(AdSensitive::getSensitives));
        List<String> sensitives = dbsensitives.stream().map(AdSensitive::getSensitives).collect(Collectors.toList());
        SensitiveWordUtil.initMap(sensitives);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0) {
            updateWmNews(wmNews, (short) 2, "文章存在敏感词");
            flag = false;
        }
        return flag;
    }

    @Autowired
    GreenImageScan greenImageScan;
    @Autowired
    GreenUrlImageScan greenUrlImageScan;
    /**
     * 阿里云图片审核
     * @param images
     * @param wmNews
     * @return
     */
    @Value("${fdfs.url}")
    private String fileUrl;
    @Autowired
    FastDFSClient fastDFSClient;

    private boolean handleimageScan(List<String> images, WmNews wmNews) {
        boolean flag = true;
        if (images == null || images.size() == 0) {
            return true;
        }
        List<byte[]> list = new ArrayList<>();
        try {
            for (String image : images) {
                String replaceImage = image.replace(fileUrl, "");
                int indexOf = replaceImage.indexOf("/");
                String groupName = replaceImage.substring(0, indexOf);
                String path = replaceImage.substring(indexOf + 1);
                byte[] bytes = fastDFSClient.download(groupName, path);
                list.add(bytes);
            }
            //网络图片校验
          // Map map = greenUrlImageScan.imageScan(images);
            Map map = greenImageScan.imageScan(list);
            String suggestion = (String) map.get("suggestion");
            if (suggestion.equals("review")) {
                updateWmNews(wmNews, (short) 3, "图片有不确定内容");
                flag = false;
            }
            if (suggestion.equals("block")) {
                updateWmNews(wmNews, (short) 2, "图片违规");
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;

    }

    /**
     * 阿里云文档审核
     * @param content
     * @return
     */
    @Autowired
    GreenTextScan greenTextScan;

    private boolean handleTextScan(String content,WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greenTextScan.greeTextScan(content);
            String suggestion = (String) map.get("suggestion");
            if (suggestion.equals("review")) {
                updateWmNews(wmNews, (short) 3, "文章需要人工审核");
                flag = false;
            }
            if (suggestion.equals("block")) {
                updateWmNews(wmNews, (short) 2, "文章违规");
                flag = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 修改自媒体文章表
     * @param wmNews
     * @param status
     * @param mesg
     */
    private void updateWmNews(WmNews wmNews, Short status, String mesg) {
        wmNews.setStatus(status);
        wmNews.setReason(mesg);
        ResponseResult responseResult = wemediaFeign.updateWmNews(wmNews);
        if (responseResult.getCode() != 0) {
            throw new RuntimeException("修改自媒体文章失败");
        }

    }

    /**
     * 取出图片和文章内容
     * @param wmNews
     * @return
     */
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String content = wmNews.getContent();
        List<Map> maps = JSON.parseArray(content, Map.class);
        List<String> images = new ArrayList<>();
        StringBuilder texts = new StringBuilder();
        for (Map map : maps) {
            if (map.get("type").equals("text")) {
                texts.append(map.get("value"));
            }
            if (map.get("type").equals("image")) {
              images.add((String) map.get("value"));
            }
        }
        if (wmNews.getImages() != null && wmNews.getImages().length() > 0) {
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("image",images);
        resultMap.put("content",texts.toString());
        return resultMap;
    }

    private void saveAppArticel(WmNews wmNews) {
      ResponseResult responseResult = saveArtive(wmNews);
        if (!responseResult.getCode().equals(0)) {
            throw new RuntimeException("保存app端文章失败");
        }
        Object articleId = responseResult.getData();
        wmNews.setArticleId((long)articleId);
        updateWmNews(wmNews,(short) 9,"已发布");

    }
    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    AdChannelMapper adChannelMapper;
    private ResponseResult saveArtive(WmNews wmNews) {
        ArticelDto dto = new ArticelDto();
        Long articleId = wmNews.getArticleId();
        if (articleId != null) {
            dto.setId(articleId);
        }
        dto.setTitle(wmNews.getTitle());
        dto.setChannelId(wmNews.getChannelId());
        dto.setLayout(wmNews.getType());
        dto.setImages(wmNews.getImages());
        dto.setContent(wmNews.getContent());
        dto.setCreatedTime(new Date());
        dto.setPublishTime(wmNews.getPublishTime());
        //频道设置
        AdChannel channel = adChannelMapper.selectById(wmNews.getChannelId());
        if(channel != null){

            dto.setChannelName(channel.getName());
        }

        //作者相关设置
        WmUser wmUser = wemediaFeign.findWmUserById(wmNews.getUserId());
        if(wmUser != null){
            dto.setAuthorName(wmUser.getName());
        }
        return articleFeign.saveApArtice(dto);
    }
}
